@page "/new-item"
@using WebUI.Model
@using WebUI.Services
@inherits WebUI.Features.AuthnComponent
@inject WebUI.Services.ItemService ItemService

<div class="section">
  <div class="container">
    <div class="content">
      <h3>Create a New Product</h3>
    </div>
  </div>
  <div class="container">
    <div class="field">
      <label class="label">Product Name</label>
      <div class="control">
        <input class="input" type="text" bind="@Model.ProductName" />
      </div>
    </div>
    <div class="field">
      <label class="label">Image</label>
      <div class="control">
        <img src="@Model.ImageUrl" name="image" alt="image" />
        <a class="button is-default" onclick="@(async () => await OnChangeImage())">Change Image</a>
      </div>
    </div>
    <div class="field">
      <label class="label">Description</label>
      <div class="control">
        <input class="input" type="text" bind="@Model.Description" />
      </div>
    </div>
    <div class="field">
      <label class="label">Price</label>
      <div class="control">
        <input class="input" type="number" bind="@Model.Price" />
      </div>
    </div>
    <div class="field">
      <div class="control">
        <a onclick="@(async () => await OnCreate())" class="button is-primary">Create</a>
      </div>
    </div>
  </div>
</div>

@functions {

  NewItemViewModel Model { get; set; } = new NewItemViewModel();

  protected Task OnChangeImage()
  {
    var randomer = new Random();
    Model.ImageUrl = $"https://picsum.photos/1200/900?image={randomer.Next(1, 500)}";
    StateHasChanged();
    return Task.CompletedTask;
  }

  async Task OnCreate()
  {
    await ItemService.CreateItem(new ItemModel
    {
      Name = Model.ProductName,
      Desc = Model.Description,
      Price = Model.Price,
      ImageUrl = Model.ImageUrl
    });

    await JsInteropService.Navigate();
  }

}
